package com.joven.shelltest.utils.mybatisplusdim;

import com.joven.shelltest.utils.encrypt.AES;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author wzj
 * @Date 2023-10-10 16:40
 **/
public class CustomTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String parameter, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(i, AES.encrypt(parameter));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        try {
            return AES.decrypt(resultSet.getString(columnName));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        try {
            return AES.decrypt(resultSet.getString(columnIndex));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        try {
            return AES.decrypt(callableStatement.getString(columnIndex));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
